<template>
  <view class="mine-information-edit-page" >
    <view class="from-box" v-if="type == 'name'">
      <view class="label">姓名</view>
      <view class="from-group">
        <input 
          v-model="filterForm.name"
          class="input-field"
          placeholder="请输入姓名"
          maxlength="11"
          @input="validatePhone"
        />
      </view>
    </view>
    <view class="from-box" v-if="type == 'sex'">
      <view class="label">性别</view>
      <view class="from-group flex">
        <label class="radio" :class="filterForm.sex === '男' ? 'active' : ''" @click="handleGender('男')">男</label>
        <label class="radio" :class="filterForm.sex === '女' ? 'active' : ''" @click="handleGender('女')">女</label>
      </view>
    </view>
    <view class="from-box" v-if="type == 'birthday'">
      <view class="label">出生日期</view>
      <view class="from-group">
        <view class="from-group picker-text" @click="isBirthPopup = true">
          {{ filterForm.birthday || '请选择' }}
          <img class="calendar-icon" src="https://www.thuguardian.com/files/small_program/icon-picker.png" alt="">
        </view>
        <!-- <picker
          :value="filterForm.birthday"
          mode="date" 
          @change="onDateChange"
          class="picker"
        >
          <view class="picker-text">
            {{ filterForm.birthday || '请选择' }}
            <img class="calendar-icon" src="https://www.thuguardian.com/files/small_program/icon-picker.png" alt="">
          </view>
        </picker> -->
      </view>
    </view>
    <view class="from-box" v-if="type == 'mobile'" >
      <view class="label">手机号</view>
      <view class="from-group">
        
        <!-- 手机号输入 -->
        <view class="input-group">
          <input 
            v-model="filterForm.mobile"
            class="input-field"
            placeholder="请输入手机号"
            type="number"
            maxlength="11"
            @input="validatePhone"
          />
        </view>

        <!-- 验证码输入 -->
        <view class="input-group code-group">
          <input
            v-model="filterForm.code"
            class="input-field"
            placeholder="请输入验证码"
            type="number"
            maxlength="6"
            @input="validateCode"
          />
          <button 
            class="get-code-btn"
            :disabled="codeBtnDisabled"
            @click="getVerifyCode"
          >
            {{ codeBtnText }}
          </button>
        </view>
      </view>
    </view>
    <view class="from-box" v-if="type == 'address'" >
      <view class="label">居住地</view>
      <view class="address-group">
        <view class="from-group picker-text" @click="isAddress = true">{{ filterForm.region_name.join('-') || '请选择所在地区' }}</view>
        <!-- <picker
          :value="filterForm.region"
          class="region-picker"
          @change="onRegionChange"
          mode="region"
        >
          <view class="picker-text">{{ filterForm.region_name.toString() || '请选择所在地区' }}</view>
        </picker> -->
        <view class="address-input">
          <!-- <textarea 
            placeholder="请输入详细地址" 
            :value="filterForm.address"
            style="width: 100%"
            @change="handleAddress"
          /> -->
          <van-field
            class="con"
            :value="filterForm.address"
            type="textarea"
            placeholder="请输入详细地址"
            :border="false"
            maxlength="200"
            :autosize="{
              maxHeight: 56,
              minHeight: 56
            }"
            clearable
            @change="handleAddress"
          />
          <img class="location-icon" src="https://www.thuguardian.com/files/small_program/icon-address.png" alt="">
        </view>
      </view>
    </view>
    <button
      class="save-btn"
      type="primary"
      @click="handelSave"
      :loading="isLoading">保存</button>

    
    <!-- 出生日期 -->
    <van-popup
      :show="isBirthPopup"
      position="bottom"
      round
      custom-style="width: 100%;"
      @close="handleBirthClose"
    >
      <van-datetime-picker
        type="date"
        :value="birthday"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onDateChange"
        @cancel="handleBirthClose"
      />
    </van-popup>
    
    <!-- 地址 -->
    <van-popup
      :show="isAddress"
      position="bottom"
      round
      custom-style="width: 100%;"
      @close="handleAddressClose"
    >
      <van-area
        :value="filterForm.region"
        :area-list="areaList"
        @confirm="onRegionChange"
        @cancel="handleAddressClose"
      />
    </van-popup>
  </view>
</template>

<script>
  import Dialog from '@/wxcomponents/vant/dialog/dialog';
  import { getInfo, getCode } from '@/api/common/index.js'
  import { fmtTimeStamp  } from '@/utils/index';
  import { areaList } from '@vant/area-data'
  import { updateName, updateSex, updateBirthday, updateMobile, updateAddress } from '@/api/mine/index.js'

  export default {
    components: {},
    data() {
      return {
        token: '',
        type: 'name',
        isLoading: false,
        userInfo: {},
        filterForm: {
          name: '',
          mobile: '',
          code: '',
          sex: '',
          birthday: '',
          address: '',
          region: [],
          region_name: []
        },
        codeBtnText: '获取验证码',
        codeBtnDisabled: false,
        agreementChecked: false,
        countdown: 60,
        // 出生日期
        isBirthPopup: false,
        birthday: new Date(1970, 1, 1).getTime(),
        minDate: new Date(1800, 1, 1).getTime(),
        maxDate: new Date().getTime(),
        // 地址
        areaList,
        isAddress: false,
        // 设备信息
        device_no: '',
        version: ''
      };
    },
    onShow() {
      this.token = wx.getStorageSync('access_token');
    },
    onLoad(options) {
      this.type = options.type
      if (this.type == 'address') {
        this.filterForm.address = options.address || ''
        this.filterForm.province = options.province || ''
        this.filterForm.city = options.city || ''
        this.filterForm.district = options.district || ''

        Object.keys(areaList['county_list']).map(v => {
          if (areaList['county_list'][v].includes(options.district)) {
           this.filterForm.region = v
          }
        })
        this.filterForm.region_name = [options.province, options.city, options.district]
      } else if (this.type == 'birthday') {
        this.filterForm[this.type] = options.value
        this.birthday = options.value ? new Date(options.value).getTime() : new Date().getTime()
      } else {
        this.filterForm[this.type] = options.value
      }

      this.getDeviceInfo()
      this.getVersion()
    },
    methods: {
      goLogin() {
        wx.navigateTo({
          url: '/pages/login/main'
        })
      },
      getDeviceInfo: function () {
        try {
          const res = wx.getDeviceInfo();
          console.log("设备信息:", res);
          this.device_no = `${res.brand}_${res.model}_${res.platform}_${this.userInfo.id}`
        } catch (e) {
          console.error("获取设备信息失败:", e);
        }
      },
      getVersion: function () {
        const accountInfo = wx.getAccountInfoSync();
        console.log("账号信息:", accountInfo);

        const miniProgram = accountInfo.miniProgram;
        if (miniProgram) {
          const version = miniProgram.version; // 获取版本号
          console.log("小程序版本号:", version);
          this.version = version || '无版本号'; // 如果没有版本号，则显示 "无版本号"
        } else {
          console.warn("无法获取小程序信息");
          this.version = '无法获取'
        }
      },
      async getDevice () {
        const res = await addDevice({
          version: this.device_no,
          no: this.version,
          province: this.filterForm.province,
          city: this.filterForm.city,
          district: this.filterForm.district,
          type: 2
        })
      },
      async getUserInfo() {
        const res = await getInfo()

        if (res.code === 200) {
          this.userInfo = res.data
          this.filterForm = {...res.data}
          wx.setStorageSync('userInfo', res.data);
        }
      },
      // 性别
      handleGender (value) {
        this.filterForm.sex = value
      },
      // 出生日期
      // onDateChange(e) {
      //   this.filterForm.birthday = e.detail.value
      // },
      onDateChange(e) {
        console.log(e, 'ebebe')
        this.isBirthPopup = false
        this.birthday = e.detail || e.detail.value
        this.filterForm.birthday = fmtTimeStamp((this.birthday /1000), true)
      },
      handleBirthClose() {
        this.isBirthPopup = false
      },
      // 地址
      // onRegionChange(e) {
      //   this.filterForm.region = e.detail.value
      //   this.filterForm.province = e.detail.value[0]
      //   this.filterForm.city = e.detail.value[1]
      //   this.filterForm.district = e.detail.value[2]
      // },
      handleAddress(e) {
        this.filterForm.address = e.detail
      },
      onRegionChange(e) {
        this.isAddress = false
        if (e.detail && e.detail.values) {
          this.filterForm.region = e.detail.values[2].code
          this.filterForm.province = e.detail.values[0].name
          this.filterForm.city = e.detail.values[1].name
          this.filterForm.district = e.detail.values[2].name
        } else {
          this.filterForm.region = e.values[2].code
          this.filterForm.province = e.values[0].name
          this.filterForm.city = e.values[1].name
          this.filterForm.district = e.values[2].name
        }
        this.filterForm.region_name = [this.filterForm.province, this.filterForm.city, this.filterForm.district]
      },
      handleAddressClose() {
        this.isAddress = false
      },
      // 手机号实时验证
      validatePhone(e) {
        const value = e.detail.value.replace(/[^\d]/g, '')
        this.filterForm.mobile = value.slice(0, 11)
      },
      // 验证码实时验证
      validateCode(e) {
        this.filterForm.code = e.detail.value.replace(/[^\d]/g, '')
      },
      // 获取验证码
      async getVerifyCode() {
        if (!/^1[3-9]\d{9}$/.test(this.filterForm.mobile)) {
          uni.showToast({ title: '请输入有效手机号', icon: 'none' })
          return
        }

        await getCode({ mobile: this.filterForm.mobile })

        this.codeBtnDisabled = true
        let timer = setInterval(() => {
          if (this.countdown <= 0) {
            clearInterval(timer)
            this.codeBtnText = '重新获取'
            this.codeBtnDisabled = false
            this.countdown = 60
            return
          }
          this.codeBtnText = `${this.countdown--}秒后重发`
        }, 1000)
      },
      // 保存姓名
      changeName () {
        if (!this.filterForm.name) {
          uni.showToast({ title: '请输入姓名', icon: 'none' })
          return
        }
        this.isLoading = true
        updateName({
          name: this.filterForm.name
        }).then(res => {
          if (res.code == 200) {
            this.isLoading = false
            uni.showToast({ title: '修改成功', icon: 'success' })
            uni.navigateBack();
          }
        })
      },
      // 保存性别
      changeSex () {
        if (!this.filterForm.sex) {
          uni.showToast({ title: '请选择性别', icon: 'none' })
          return
        }
        this.isLoading = true
        updateSex({
          sex: this.filterForm.sex
        }).then(res => {
          if (res.code == 200) {
            this.isLoading = false
            uni.showToast({ title: '修改成功', icon: 'success' })
            wx.navigateBack();
          }
        })
      },
      // 获取验证码
      async getVerifyCode() {
        if (!/^1[3-9]\d{9}$/.test(this.filterForm.mobile)) {
          uni.showToast({ title: '请输入有效手机号', icon: 'none' })
          return
        }

        // 这里添加发送验证码的API请求
        const res = await getCode({
          mobile: this.filterForm.mobile
        })
        if (res.code == 200) {
          this.codeBtnDisabled = true
          let timer = setInterval(() => {
            if (this.countdown <= 0) {
              clearInterval(timer)
              this.codeBtnText = '重新获取'
              this.codeBtnDisabled = false
              this.countdown = 60
              return
            }
            this.codeBtnText = `${this.countdown--}秒后重发`
          }, 1000)
        }
      },
      // 保存手机号
      changeMobile () {
        if (!this.filterForm.mobile) {
          uni.showToast({ title: '请输入手机号', icon: 'none' })
          return
        }
        if (!this.filterForm.code) {
          uni.showToast({ title: '请输入验证码', icon: 'none' })
          return
        }
        this.isLoading = true
        updateMobile({
          mobile: this.filterForm.mobile,
          code: this.filterForm.code
        }).then(res => {
          if (res.code == 200) {
            this.isLoading = false
            uni.showToast({ title: '修改成功', icon: 'success' })
            wx.navigateBack();
          }
        })
      },
      // 保存生日
      changBirthday () {
        if (!this.filterForm.birthday) {
          uni.showToast({ title: '请选择你的生日', icon: 'none' })
          return
        }
        this.isLoading = true
        updateBirthday({
          birthday: this.filterForm.birthday
        }).then(res => {
          if (res.code == 200) {
            this.isLoading = false
            uni.showToast({ title: '修改成功', icon: 'success' })
            wx.navigateBack();
          }
        })
      },
      // 保存地址
      changAddress() {
        if (!this.filterForm.region || !this.filterForm.address) {
          uni.showToast({ title: '请完善你的地址信息', icon: 'none' })
          return
        }
        this.isLoading = true
        updateAddress({
          province: this.filterForm.province,
          city: this.filterForm.city,
          district: this.filterForm.district,
          address: this.filterForm.address,
        }).then(res => {
          if (res.code == 200) {
            this.isLoading = false
            uni.showToast({ title: '修改成功', icon: 'success' })
            this.getDevice()
            wx.navigateBack();
          }
        })
      },
      handelSave () {
        if (this.type == 'name') {
          this.changeName()
        }
        if (this.type === 'sex') {
          this.changeSex()
        }
        if (this.type === 'mobile') {
          this.changeMobile()
        }
        if (this.type === 'birthday') {
          this.changBirthday()
        }
        if (this.type === 'address') {
          this.changAddress()
        }
      }
    },
  };
</script>

<style lang="less" scoped>
  .mine-information-edit-page {
    padding: 20px 30px;
    margin-bottom: env(12px + safe-area-inset-bottom);
    background: #fff;

    .from-box {
      margin-bottom: 24px;
    }
    .label {
      font-size: 18px;
      color: rgba(0, 0, 0, .85);
      line-height: 23px;
    }
    .from-group {
      margin-top: 16px;
      &.flex {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }

      .input-field {
        display: block;
        padding: 0 12px;
        height: 50px;
        font-size: 18px;
        color: rgba(0, 0, 0, .85);
        line-height: 48px;
        border: 1px solid #00AFCB;
        border-radius: 8px;
      }

      .radio {
        width: 148px;
        height: 50px;
        line-height: 48px;
        text-align: center;
        font-size: 18px;
        color: rgba(0, 0, 0, .65);
        background: #E5FAF7;
        border: 1px solid #E5FAF7;
        border-radius: 8px;
        &.active {
          color: #00AFCB;
          border-color: #00AFCB;
        }
      }

      .input-group {
        margin-bottom: 24px;
        position: relative;
        
        .input-field {
          height: 48px;
          padding: 0 16px;
          border: 2rpx solid rgba(0, 0, 0, .1);
          border-radius: 8px;
          font-size: 18px;
          
          &::placeholder {
            color: #999;
          }
        }
      }
      .code-group {
        display: flex;
        align-items: center;
        
        .input-field {
          flex: 1;
          margin-right: 20rpx;
        }
        
        .get-code-btn {
          width: 124px;
          height: 48px;
          padding: 0;
          line-height: 48px;
          color: #00AFCB;
          font-size: 14px;
          background: #fff;
          border-radius: 24px;
          border: 1px solid #00AFCB;
          
          &[disabled] {
            background: #fff;
            border: 1px solid #00AFCB;
          }
        }
      }

    }

    
    .picker-text {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 12px;
      height: 48px;
      font-size: 18px;
      color: rgba(0, 0, 0, .85);
      line-height: 48px;
      border: 1px solid #00AFCB;
      border-radius: 8px;
      box-sizing: border-box;
    }
    // .picker {
    //   padding: 0 12px;
    //   height: 50px;
    //   font-size: 18px;
    //   color: rgba(0, 0, 0, .85);
    //   line-height: 48px;
    //   border: 1px solid #00AFCB;
    //   border-radius: 8px;
    // }
    // 图标样式需要替换实际图标
    .calendar-icon,
    .location-icon {
      display: inline-block;
      width: 24px;
      height: 24px;
    }


    .address-group {
      margin-top: 16px;
      .region-picker {
        height: 25px;
        border: 1px solid rgba(0,0,0,0.1);
        border-radius: 8px;
        padding: 12px;
        font-size: 18px;
      }
      
      .address-input {
        position: relative;
        height: 56px;
        border: 1px solid rgba(0,0,0,0.1);
        border-radius: 8px;
        padding: 12px;
        padding-right: 36px;
        font-size: 18px;
        margin-top: 16px;
        overflow: hidden;
        
        .location-icon {
          position: absolute;
          right: 20rpx;
          top: 50%;
          transform: translateY(-50%);
          width: 20px;
          height: 20px;
        }
      }
    }




    .save-btn {
      height: 48px;
      line-height: 48px;
      border-radius: 24px;
      background: linear-gradient(93deg, #00AFCB 19.12%, #1097B4 62.08%);
    }
  }


  /deep/ .van-cell {
    padding: 0 0 !important;
    height: 100%;
    font-size: 18px !important;
  }
</style>
